package org.jackysoft.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.data.AbstractDataProvider;
import org.jackysoft.entity.HtmlFormTemplate;
import org.jackysoft.mapper.HtmlTemplateMapper;
import org.jackysoft.service.HtmlTemplateService;
import org.jackysoft.util.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

@Service
public class HtmlTemplateServiceImpl extends
		AbstractDataProvider<HtmlFormTemplate> implements HtmlTemplateService {
	static final Log logger = LogFactory.getLog(HtmlTemplateServiceImpl.class);
	
	
	@Resource
	HtmlTemplateMapper mapper;
	public HtmlTemplateServiceImpl() {
		super();
	}


	@Override
	public void upload(Part file, HtmlFormTemplate bean) {
				
		try {
			
			UUID uid = UUID.randomUUID();
			String id = uid.toString();
			
			OutputStream out = new FileOutputStream(String.format("%s%s%s%s", context.HTMLBase,File.separator,id,".html"));
			IOUtils.copy(file.getInputStream(), out);
			bean.setName(StringUtils.splitPreFileName(file.getSubmittedFileName()));
			bean.setPath("/"+id+".html");
			bean.setCreateDate(DateTime.now().getMillis());
		    
			mapper.inert(bean);
	
		} catch (IOException e) {
			logger.error(e);			
		}
	}
	
	
	@Override
	public void update(String id, String content) throws DataAccessException {
		try {
			
		
		OutputStream out = new FileOutputStream(String.format("%s%s%s%s", context.HTMLBase,File.separator,id,".html"));
		StringReader sr = new StringReader(content);
		IOUtils.copy(sr, out);
		

		} catch (IOException e) {
			logger.error(e);			
		}
	}



	
	protected InputStream loadTemplate(String id) {
		String path = String.format("%s%s%s%s", context.HTMLBase,File.separator,id,".html");
		InputStream input = null; 
		try {
			input = new BufferedInputStream(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			logger.error(e);
		}
		
		return input;
	}


	@Override
	public StringWriter loadToWriter(String id) {
		StringWriter sw =  new StringWriter();
		InputStream input = this.loadTemplate(id);
		try {
			IOUtils.copy(input, sw);
			input.close();
		} catch (IOException e) {
			logger.error(e);
		}
		return sw;
	}

}